<template>
  <div class="life-entity-detail">
    <a-page-header :title="entity?.name || '生命体详情'" @back="() => $router.go(-1)">
      <template #extra>
        <a-space>
          <a-button @click="editEntity">编辑</a-button>
          <a-button type="primary" @click="refreshData">刷新</a-button>
        </a-space>
      </template>
    </a-page-header>

    <div v-if="loading" class="loading-container">
      <a-spin size="large" />
    </div>

    <div v-else-if="entity" class="detail-content">
      <a-row :gutter="[16, 16]">
        <!-- 基本信息 -->
        <a-col :xs="24" :lg="12">
          <a-card title="基本信息" :bordered="false">
            <a-descriptions :column="1">
              <a-descriptions-item label="名称">
                {{ entity.name }}
              </a-descriptions-item>
              <a-descriptions-item label="类型">
                <a-tag :color="getTypeColor(entity.type)">
                  {{ getTypeLabel(entity.type) }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="状态">
                <a-badge
                  :status="getStatusBadge(entity.status)"
                  :text="getStatusLabel(entity.status)"
                />
              </a-descriptions-item>
              <a-descriptions-item label="描述">
                {{ entity.description || '暂无描述' }}
              </a-descriptions-item>
              <a-descriptions-item label="创建时间">
                {{ formatDate(entity.createdAt) }}
              </a-descriptions-item>
              <a-descriptions-item label="更新时间">
                {{ formatDate(entity.updatedAt) }}
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>

        <!-- 意识状态 -->
        <a-col :xs="24" :lg="12">
          <a-card title="意识状态" :bordered="false">
            <div v-if="consciousnessState">
              <a-space direction="vertical" style="width: 100%">
                <div class="consciousness-item">
                  <span>意识等级</span>
                  <a-tag :color="getConsciousnessColor(consciousnessState.level)">
                    {{ getConsciousnessLabel(consciousnessState.level) }}
                  </a-tag>
                </div>

                <div class="consciousness-metric">
                  <span>觉知度</span>
                  <a-progress
                    :percent="consciousnessState.awareness"
                    size="small"
                    :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }"
                  />
                </div>

                <div class="consciousness-metric">
                  <span>专注度</span>
                  <a-progress
                    :percent="consciousnessState.focus"
                    size="small"
                    :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }"
                  />
                </div>

                <div class="consciousness-metric">
                  <span>创造力</span>
                  <a-progress
                    :percent="consciousnessState.creativity"
                    size="small"
                    :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }"
                  />
                </div>

                <div class="consciousness-metric">
                  <span>共情能力</span>
                  <a-progress
                    :percent="consciousnessState.empathy"
                    size="small"
                    :stroke-color="{ '0%': '#108ee9', '100%': '#87d068' }"
                  />
                </div>
              </a-space>
            </div>
            <a-empty v-else description="暂无意识状态数据" />
          </a-card>
        </a-col>

        <!-- 数字DNA -->
        <a-col :xs="24" :lg="12">
          <a-card title="数字DNA" :bordered="false">
            <div v-if="digitalDNA">
              <a-descriptions :column="1">
                <a-descriptions-item label="DNA序列">
                  <a-typography-text code>
                    {{ digitalDNA.sequence.substring(0, 50) }}...
                  </a-typography-text>
                </a-descriptions-item>
                <a-descriptions-item label="世代">
                  第 {{ digitalDNA.generation }} 代
                </a-descriptions-item>
                <a-descriptions-item label="特征数量">
                  {{ Object.keys(digitalDNA.traits).length }} 个特征
                </a-descriptions-item>
              </a-descriptions>

              <a-divider />

              <h4>主要特征</h4>
              <a-space wrap>
                <a-tag v-for="(value, key) in digitalDNA.traits" :key="key" color="blue">
                  {{ key }}: {{ value }}
                </a-tag>
              </a-space>
            </div>
            <a-empty v-else description="暂无DNA数据" />
          </a-card>
        </a-col>

        <!-- 关系网络 -->
        <a-col :xs="24" :lg="12">
          <a-card title="关系网络" :bordered="false">
            <div v-if="relationships.length > 0">
              <a-list :data-source="relationships" size="small">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <a-list-item-meta>
                      <template #title>
                        <a-space>
                          <span>{{ item.targetEntityName }}</span>
                          <a-tag size="small">{{ item.relationshipType }}</a-tag>
                        </a-space>
                      </template>
                      <template #description> 强度: {{ item.strength }}/100 </template>
                    </a-list-item-meta>
                  </a-list-item>
                </template>
              </a-list>
            </div>
            <a-empty v-else description="暂无关系数据" />
          </a-card>
        </a-col>
      </a-row>

      <!-- 活动历史 -->
      <a-row :gutter="[16, 16]" style="margin-top: 16px">
        <a-col :span="24">
          <a-card title="活动历史" :bordered="false">
            <a-timeline>
              <a-timeline-item
                v-for="activity in activityHistory"
                :key="activity.id"
                :color="getActivityColor(activity.type)"
              >
                <div class="activity-content">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-description">{{ activity.description }}</div>
                  <div class="activity-time">{{ formatDate(activity.timestamp) }}</div>
                </div>
              </a-timeline-item>
            </a-timeline>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <a-result v-else status="404" title="生命体不存在" sub-title="请检查ID是否正确">
      <template #extra>
        <a-button type="primary" @click="$router.push('/life-entities')"> 返回列表 </a-button>
      </template>
    </a-result>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { lifeEntityApi } from '@/api/lifeEntity'
import { consciousnessApi } from '@/api/consciousness'
import { networkApi } from '@/api/network'
import type {
  LifeEntity,
  LifeEntityType,
  LifeEntityStatus,
  ConsciousnessState,
  ConsciousnessLevel,
  DigitalDNA,
  LifeEntityRelationship,
} from '@/api/types'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const entity = ref<LifeEntity | null>(null)
const consciousnessState = ref<ConsciousnessState | null>(null)
const digitalDNA = ref<DigitalDNA | null>(null)
const relationships = ref<LifeEntityRelationship[]>([])
const activityHistory = ref([
  {
    id: 1,
    type: 'create',
    title: '生命体创建',
    description: '生命体成功创建并初始化',
    timestamp: '2024-01-15T10:30:00Z',
  },
  {
    id: 2,
    type: 'update',
    title: '意识状态更新',
    description: '意识等级提升到中级',
    timestamp: '2024-01-16T14:20:00Z',
  },
  {
    id: 3,
    type: 'interaction',
    title: '建立新关系',
    description: '与其他生命体建立协作关系',
    timestamp: '2024-01-17T09:15:00Z',
  },
])

// 获取类型相关方法（复用之前的代码）
const getTypeColor = (type: LifeEntityType) => {
  const colorMap = {
    CORPORATE: 'blue',
    URBAN: 'green',
    CONCEPTUAL: 'purple',
    INDIVIDUAL: 'orange',
    HYBRID: 'red',
    SYSTEM: 'cyan',
  }
  return colorMap[type]
}

const getTypeLabel = (type: LifeEntityType) => {
  const labelMap = {
    CORPORATE: '企业',
    URBAN: '城市',
    CONCEPTUAL: '概念',
    INDIVIDUAL: '个体',
    HYBRID: '混合',
    SYSTEM: '系统',
  }
  return labelMap[type]
}

const getStatusBadge = (status: LifeEntityStatus) => {
  const badgeMap = {
    ACTIVE: 'success',
    INACTIVE: 'default',
    EVOLVING: 'processing',
    DORMANT: 'warning',
  }
  return badgeMap[status] as any
}

const getStatusLabel = (status: LifeEntityStatus) => {
  const labelMap = {
    ACTIVE: '活跃',
    INACTIVE: '非活跃',
    EVOLVING: '进化中',
    DORMANT: '休眠',
  }
  return labelMap[status]
}

const getConsciousnessColor = (level: ConsciousnessLevel) => {
  const colorMap = {
    BASIC: 'default',
    INTERMEDIATE: 'blue',
    ADVANCED: 'green',
    TRANSCENDENT: 'purple',
  }
  return colorMap[level]
}

const getConsciousnessLabel = (level: ConsciousnessLevel) => {
  const labelMap = {
    BASIC: '基础',
    INTERMEDIATE: '中级',
    ADVANCED: '高级',
    TRANSCENDENT: '超越',
  }
  return labelMap[level]
}

const getActivityColor = (type: string) => {
  const colorMap = {
    create: 'green',
    update: 'blue',
    interaction: 'orange',
    alert: 'red',
  }
  return colorMap[type as keyof typeof colorMap] || 'blue'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载数据
const loadData = async () => {
  const entityId = route.params.id as string
  if (!entityId) {
    router.push('/life-entities')
    return
  }

  loading.value = true
  try {
    // 并行加载所有数据
    const [entityData, consciousnessData, relationshipsData] = await Promise.allSettled([
      lifeEntityApi.getById(entityId),
      consciousnessApi.getByLifeEntityId(entityId),
      networkApi.getRelationships({ sourceEntityId: entityId }),
    ])

    if (entityData.status === 'fulfilled') {
      entity.value = entityData.value
    }

    if (consciousnessData.status === 'fulfilled') {
      consciousnessState.value = consciousnessData.value
    }

    if (relationshipsData.status === 'fulfilled') {
      relationships.value = relationshipsData.value
    }

    // 模拟数字DNA数据（实际项目中会从API获取）
    digitalDNA.value = {
      id: '1',
      lifeEntityId: entityId,
      sequence: 'ATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCG',
      traits: {
        创新能力: 85,
        协作倾向: 72,
        学习速度: 90,
        适应性: 78,
      },
      generation: 3,
      createdAt: '2024-01-15T10:30:00Z',
      updatedAt: '2024-01-17T09:15:00Z',
    }
  } catch (error) {
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadData()
  message.success('数据已刷新')
}

// 编辑实体
const editEntity = () => {
  // 这里可以打开编辑模态框或跳转到编辑页面
  message.info('编辑功能待实现')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.life-entity-detail {
  padding: 0;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.detail-content {
  margin-top: 16px;
}

.consciousness-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.consciousness-metric {
  margin-bottom: 16px;
}

.consciousness-metric span {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.activity-content {
  display: flex;
  flex-direction: column;
}

.activity-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.activity-description {
  color: #666;
  margin-bottom: 4px;
}

.activity-time {
  font-size: 12px;
  color: #999;
}
</style>
